using System;
using UnityEngine;

namespace EntityKit.Runtime
{
    public abstract class EntityComponent<T> : MonoBehaviour, IEntityComponent where T : class, IEntity
    {
        [HideInInspector] public T OwnerEntity;
        private EventGroup mEventGroup = null;
        public bool IsInit { get; private set; }

        public virtual void OnInit(IEntity ownerEntity)
        {
            if (IsInit)
                throw new Exception("组件已经初始化了.");
            IsInit = true;
            OwnerEntity = ownerEntity as T;
            mEventGroup = new EventGroup();
            BindService.AutoBind(this);
        }

        public virtual void OnUpdate()
        {
            if (!IsInit) return;
        }

        public virtual void OnRelease()
        {
            if (!IsInit)
                throw new System.Exception("不能释放一个没有初始化的组件.");
            IsInit = false;
            mEventGroup.RemoveAllListener();
            BindService.Unbind(this);
            try
            {
                if (gameObject != null && !gameObject.Equals(null))
                    Destroy(gameObject);
            }
            catch (Exception e)
            {
#if UNITY_EDITOR
                Debug.LogWarning($"Release Component {this.name} failed: {e.Message} StackTrace {e.StackTrace}");
#else
                Debug.LogError($"Release Component {this.name} failed: {e.Message} StackTrace {e.StackTrace}");
#endif
            }
        }

        public R GetEntityComponent<R>() where R : class, IEntityComponent
        {
            return OwnerEntity.GetEntityComponent<R>() as R;
        }

        public virtual void SetActive(bool active)
        {
            gameObject.SetActive(active);
        }

        /// <summary>
        /// 添加事件监听器
        /// </summary>
        protected void AddEventListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
        {
            mEventGroup.AddListener<TEvent>(listener);
        }

        /// <summary>
        /// 发送事件消息
        /// </summary>
        protected void SendEventMessage(IEventMessage message)
        {
            EventKit.SendMessage(message);
        }

        /// <summary>
        /// 延迟发送事件消息
        /// </summary>
        protected void PostEventMessage(IEventMessage message)
        {
            EventKit.PostMessage(message);
        }
    }
}